import { createRouter, createWebHashHistory } from 'vue-router'
import { basicRoutes as routes } from './basicRoutes'
import { ElNotification } from 'element-plus';
import {beforeEach, afterEach} from './scrollBehavior';
// @ts-ignore
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// @ts-ignore
import tool from "@/utils/tool";

const config = {
    APP_NAME: import.meta.env.VITE_APP_TITLE,
    APP_VERSION: import.meta.env.VITE_APP_VERSION,
}

let userRoutes:any = []

let viewModulesTmp = import.meta.glob('@/views/**/index.vue');
// console.log('viewModulesTmp', viewModulesTmp);
let viewModules = {};
// @ts-ignore
Object.keys(viewModulesTmp).forEach((key) => {
    // 判断如果是错误页面的，跳过
    if(key.indexOf('/errorPage/')>-1){
        return
    }
    // @ts-ignore
    viewModules[key.replace('/src/views/', '').replace(/(\.\/|\/index\.vue)/g, '')] = viewModulesTmp[key];
})
// console.log('viewModules', viewModules);

//系统特殊路由
const routes_404 = {
    path: "/:pathMatch(.*)*",
    hidden: true,
    component: () => import(/* webpackChunkName: "404" */ '@/sysViews/errorPage/404.vue'),
}
let routes_404_r = ()=>{}

export const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

//判断是否已加载过动态/静态路由
var isGetRouter = false;

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    //动态标题
    document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`

    let token = tool.data.getToken();

    if(to.path === "/login"){
        //删除路由(替换当前layout路由)
        router.addRoute(routes[0])
        //删除路由(404)
        routes_404_r()
        isGetRouter = false;
        next();
        return false;
    }

    if(!token){
        next({
            path: '/login'
        });
        return false;
    }

    //整页路由处理
    if(to.meta.fullpage){
        to.matched = [to.matched[to.matched.length-1]]
    }
    //加载动态/静态路由
    if(!isGetRouter){
        let apiMenu = tool.data.getMenu()
        let userInfo = tool.data.getUserInfo()
        if (!userInfo) {
            next({
                path: '/login'
            });
            return false;
        }
        let userMenu = treeFilter(userRoutes, (node:any) => {
            // @ts-ignore
            return node.meta.role ? node.meta.role.filter((item:any) => userInfo.role.indexOf(item)>-1).length > 0 : true
        });
        let menu = [...userMenu, ...apiMenu]
        let menuRouter = filterAsyncRouter(menu)
        menuRouter = flatAsyncRoutes(menuRouter)
        menuRouter.forEach((item:any) => {
            router.addRoute("layout", item)
        })
        routes_404_r = router.addRoute(routes_404)
        if (to.matched.length == 0) {
            router.push(to.fullPath);
        }
        isGetRouter = true;
    }
    beforeEach(to, from)
    next();
});

router.afterEach((to, from) => {
    // @ts-ignore
    afterEach(to, from)
    NProgress.done()
});

router.onError((error) => {
    NProgress.done();
    console.error(error);
    ElNotification.error({
        title: '路由错误',
        message: error.message
    });
});

export function getMenu (){
    var apiMenu = tool.data.getMenu()
    let userInfo = tool.data.getUserInfo()
    let userMenu = treeFilter(userRoutes, (node:any) => {
        // @ts-ignore
        return node.meta.role ? node.meta.role.filter((item:any) => userInfo.role.indexOf(item)>-1).length > 0 : true
    })
    return [...userMenu, ...apiMenu]
}

//转换
function filterAsyncRouter(routerMap:any) {
    const accessedRouters:any = []
    routerMap.forEach((item:any) => {
        item.meta = item.meta?item.meta:{};
        //处理外部链接特殊路由
        if(item.meta.type=='iframe'){
            item.meta.url = item.path;
            item.path = `/i/${item.name}`;
        }

        //MAP转路由对象
        var route = {
            path: item.path,
            name: item.name,
            meta: item.meta,
            redirect: item.redirect,
            children: item.children ? filterAsyncRouter(item.children) : null,
            component: loadComponent(item.component)
        }
        accessedRouters.push(route)
    })
    return accessedRouters
}
// @ts-ignore
function loadComponent(component){
    if (!component) {
        return () => import(`@/sysViews/errorPage/empty.vue`)
    }

    // @ts-ignore
    if (viewModules[component]) {
        // @ts-ignore
        return viewModules[component];
    }
}

//路由扁平化
function flatAsyncRoutes(routes:any, breadcrumb=[]) {
    let res: any[] = []
    routes.forEach((route:any) => {
        const tmp = {...route}
        if (tmp.children) {
            let childrenBreadcrumb = [...breadcrumb]
            // @ts-ignore
            childrenBreadcrumb.push(route)
            let tmpRoute = { ...route }
            tmpRoute.meta.breadcrumb = childrenBreadcrumb
            delete tmpRoute.children
            res.push(tmpRoute)
            let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = [...breadcrumb]
            // @ts-ignore
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = tmpBreadcrumb
            res.push(tmp)
        }
    })
    return res
}

//过滤树
// @ts-ignore
function treeFilter(tree, func) {
    return tree.map((node:any) => ({ ...node })).filter((node:any) => {
        node.children = node.children && treeFilter(node.children, func)
        return func(node) || (node.children && node.children.length)
    })
}


export function setupRouter(app: any) {
    app.use(router)
}
